package com.woniu.adapter;


import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.outlet.dao.SystemLogPoMapper;
import com.woniu.outlet.po.SystemLogPo;
import com.woniu.outlet.redis.RedisRepo;
import com.woniu.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class SystemLogAdapter {

    @Autowired
    private SystemLogPoMapper systemLogPoMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedisRepo redisRepo;




    public List<SystemLogPo> findSystemLogs() throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String str = redisRepo.findRedisRepo("systemLog:list");
        List<SystemLogPo> lists = new ArrayList<>();
        if (!StringUtils.isEmpty(str)) {
            lists = mapper.readValue(str, new TypeReference<List<SystemLogPo>>() {
            });
            return lists;
        }
        lists = systemLogPoMapper.selectByExample(null);
        //存到redis
        redisRepo.saveRedisRepo("systemLog:list",mapper.writeValueAsString(lists));
        return lists;
    }

    public SystemLogPo getSystemLogById(Long id) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String str = redisRepo.findRedisRepo("systemLog:" + id);
        SystemLogPo systemLogPo = null;
        if (!StringUtils.isEmpty(str)) {
            systemLogPo = mapper.readValue(str, new TypeReference<SystemLogPo>() {
            });
            return systemLogPo;
        }
        systemLogPo = systemLogPoMapper.selectByPrimaryKey(id);
        //存到redis
        redisRepo.saveRedisRepo("systemLog:"+id,mapper.writeValueAsString(systemLogPo));
        return systemLogPo;
    }

    public void addSystemLogPo(SystemLogPo systemLogPo){
        Date date = new Date();
        systemLogPo.setOperationDate(date);

        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String strToken = ops.get("username");
        //token有效
        String username = JwtTokenUtil.getUserId(strToken);
        systemLogPo.setLoginUser(username);
        systemLogPoMapper.insert(systemLogPo);
        redisRepo.deleteRedisRepo("systemLog:list");

    }

    public void updateSystemLogPo(SystemLogPo systemLogPo){
        systemLogPoMapper.updateByPrimaryKeySelective(systemLogPo);
        redisRepo.deleteRedisRepo("systemLog:list");
    }

    public void deleteSystemLogPoById(Long id){
        systemLogPoMapper.deleteByPrimaryKey(id);
        redisRepo.deleteRedisRepo("systemLog:list");
    }
}
